﻿using Brc_DSB.GetWay.Configuration;
using Brc_DSB.GetWay.Model;
using Dapper;
using Ocelot.Cache;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Brc_DSB.GetWay.DataBase
{
    public class AuthRepository : IAuthRepository
    {
        private readonly DbConfiguration _option;
        private readonly IOcelotCache<List<ServiceAuthModel>> _cache;
        public AuthRepository(DbConfiguration option, IOcelotCache<List<ServiceAuthModel>> cache)
        {
            _option = option;
            _cache = cache;
        }

        public async Task<bool> CheckClientAuthenticationAsync(string clientId, string path)
        {
            var sql = @"
SELECT 
    C.ReRouteId AS RouteId,
    C.UpstreamPathTemplate AS UpStreamPath
FROM 
    [dbo].[Bas_ServiceAuth] A
INNER JOIN 
    [dbo].[Bas_System] B 
ON 
    A.[SystemId]=B.[Id]
INNER JOIN 
    [dbo].[GetWay_ReRoute] C
ON 
    A.[ReRouteId]=C.[ReRouteId]
WHERE 
	C.[InfoStatus]=1 
	AND 
	A.[SystemId]=@SystemId";
            using (var connection = new SqlConnection(_option.DbConnectionStrings))
            {
                //如果启用了权限缓存，那么久先从缓存中取，取不到就去数据库取，然后放入缓存
                List<ServiceAuthModel> authResult = null;
                var key = clientId;
                if (_option.ClientAuthorizationCacheTime > 0)
                {                   
                    authResult = _cache.Get(key, "ClientAuth");
                }
                if(authResult==null)
                {
                    authResult = (await connection.QueryAsync<ServiceAuthModel>(sql, new { SystemId = clientId }))?.AsList();
                    _cache.Add(key, authResult, TimeSpan.FromMinutes(_option.ClientAuthorizationCacheTime), "ClientAuth");
                }
                return authResult.Any(i => i.UpStreamPath == path);
            }
        }
    }
}
